package com.example.fun.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.fun.R;
import com.example.fun.activity.Application;
import com.example.fun.activity.CollectionActivity;
import com.example.fun.activity.LoginActivity;
import com.example.fun.adapter.MineAdapter;
import com.example.fun.bean.LoginBean;
import com.example.fun.bean.MineBean;
import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MineFragment extends Fragment {
    private static final String TAG = "MineFragment";
    //    private ConstraintLayout clMine;
    private Context mcontext;
    private ImageView imgIcon;
    private TextView tvUserName;
    private TextView tvAboutAuthor;
    private TextView tvCoin;
    private Button btnLoginOut;
    private LinearLayout layoutCollect;
    private List<MineBean.DataDTO.UserInfoDTO> mineBeanList = new ArrayList<>();
    //    private MineAdapter mineAdapter;
    private int loginStatus;

    public static Fragment newInstance() {
        return new MineFragment();
    }

    @NonNull
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);

        initView(view);

//        initLogin();
        SharedPreferences getDataPreferences = this.getActivity().getSharedPreferences("get_token", Context.MODE_PRIVATE);
        getDataPreferences = getActivity().getSharedPreferences("get_token", LoginActivity.MODE_PRIVATE);
        String getUserName = getDataPreferences.getString("username","login");
        String getNickName = getDataPreferences.getString("nickName","aboutAuthor");
        int getCoinCount = getDataPreferences.getInt("coinCount", 0);
        String coin = String.valueOf(getCoinCount);
        tvUserName.setText(getUserName);
        tvAboutAuthor.setText(getNickName);
        tvCoin.setText(coin);

        String getIcon = getDataPreferences.getString("icon", "");
        if(getIcon.equals("")){
            imgIcon.setImageResource(R.drawable.icon_register);
        }

//        if(tvUserName.equals("login")){
//            Toast.makeText(getActivity(), "请先登录！", Toast.LENGTH_LONG).show();
//        }

        tvUserName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
            }
        });

        layoutCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CollectionActivity.class);
                startActivity(intent);
            }
        });

        btnLoginOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        initLoginOut();
                    }
                }.start();
            }
        });

        return view;

    }

    private void initView(View view) {
        imgIcon = view.findViewById(R.id.img_photo);
        tvUserName = view.findViewById(R.id.tv_goLogin);
        tvAboutAuthor = view.findViewById(R.id.tv_aboutAuthor);
        tvCoin = view.findViewById(R.id.tv_coin);
        btnLoginOut = view.findViewById(R.id.btn_logOut);
        layoutCollect = view.findViewById(R.id.layout_collection);

    }

    public void initLoginOut() {
        String address = "https://wanandroid.com//user/lg/userinfo/json";
        OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(HomeFragment.getCookieJar())
                .build();
        Request request = new Request.Builder()
                .url(address)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity().getApplicationContext(), "退出失败，请检查网络", Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                if (response.code() == 200) {
                    String mineBody = response.body().string();
                    Gson gson = new Gson();
                    MineBean mineBean = gson.fromJson(mineBody, MineBean.class);
                    int mineResultCode = mineBean.getErrorCode();
                    String mineResultMsg = mineBean.getErrorMsg();
                    Log.i(TAG, "mineResultCode: " + mineResultCode);
                    Log.i(TAG, "返回状态码结果: " + mineResultMsg);
                    Log.i(TAG, "mineBody: " + mineBody);
//                    if(mineResultMsg.equals("请先登录！")){
//                        getActivity().runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Toast.makeText(getActivity(), "请先登录！", Toast.LENGTH_LONG).show();
//                                Log.d(TAG, "initLoginOut: " + "请先登录！");
//                                loginStatus = 0;
//                                SharedPreferences sSharedPreferences = getActivity().getSharedPreferences("loginStatue", 0);
//                                SharedPreferences.Editor sEditor = sSharedPreferences.edit();
//                                sEditor.putInt("loginStatus", loginStatus);
//                                sEditor.commit();
//                                Context context = getActivity();
//                                Intent intent = new Intent(context, LoginActivity.class);
//                                context.startActivity(intent);
////                                getCookieJar();
////                                Log.i(TAG, "getCookieJar: " + getCookieJar());
//                            }
//                        });
//                    }else {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                HomeFragment.clearCookie();
                                Toast.makeText(getActivity(), "退出成功！", Toast.LENGTH_LONG).show();
                                Log.i(TAG, "initLoginOut: " + "退出成功！");
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                startActivity(intent);
                            }
                        });
//                    }

                }
            }
        });
    }
//
//    @Override
//    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
//        super.onActivityCreated(savedInstanceState);
//
//        onClickListener();
//    }
//
//    private void onClickListener() {
//
//        tvUserName.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(getActivity(), LoginActivity.class);
//                startActivity(intent);
//            }
//        });
//    }


}
